import React, { useState, useEffect, useRef } from 'react'
import { Popconfirm, Button, Modal, Form, Radio, Tag, message, Tooltip } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined, FormOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import { QuillEditor } from 'components'
import { ProTable } from '@ant-design/pro-components';
import { history } from 'umi';

const ArticleManage = ({ articleList, dispatch, userInfo }) => {
  useEffect(() => {
    tableRef.current.reload()// 刷新表格
  }, [articleList])
  const userType = userInfo.userType
  // 显示 点赞、反对、浏览量
  const [articleStatus, setArticleStatus] = useState(false)
  const tableRef = useRef();
  const [isReview, setIsReview] = useState(false)
  const [isArticle, setIsArticle] = useState(false)
  const [articleData, setArticleData] = useState([])
  const [form] = Form.useForm();
  const statusFilters = [
    { text: '待审核', value: 1 },
    { text: '已通过', value: 2 },
    { text: '不通过', value: 3 },
  ];

  {/* 详情里面显示标题、内容、作者、获赞数、不喜欢、查看数、更新时间 */ }
  const columns = [
    userType === 0 && {
      title: '文章id', dataIndex: 'articleId', key: 'articleId', align: 'center', search: false,
      sorter: (a, b) => a.articleId - b.articleId,
    },
    { title: '文章标题', dataIndex: 'title', key: 'title', align: 'center', ellipsis: true, },
    userType === 0 && { title: '作者', dataIndex: 'displayName', key: 'displayName', align: 'center', },
    userType !== 0 && {
      title: '获赞数', dataIndex: 'like', key: 'like', align: 'center', search: false,
      sorter: (a, b) => b.like - a.like
    },
    userType !== 0 && {
      title: '反对数', dataIndex: 'disLike', key: 'disLike', align: 'center', search: false,
      sorter: (a, b) => b.disLike - a.disLike
    },
    userType !== 0 && {
      title: '收藏', dataIndex: 'collectCount', key: 'collectCount', align: 'center', search: false,
      sorter: (a, b) => b.collectCount - a.collectCount
    },
    userType !== 0 && {
      title: '浏览量', dataIndex: 'view', key: 'view', align: 'center', search: false,
      sorter: (a, b) => b.view - a.view
    },

    {
      title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',
      sorter: (a, b) => new Date(a.updateTime) - new Date(b.updateTime)
    },
    {
      title: '文章状态', dataIndex: 'status', key: 'status', align: 'center', search: false,
      sorter: (a, b) => a.status - b.status,
      // .filter(Boolean)  //过滤掉为null的字段
      // 解决了在 admin 用户下 显示了一个空列表项
      filters: [userType !== 0 && { text: '草稿', value: 0 }, ...statusFilters].filter(Boolean),
      onFilter: (value, record) => record.status === value,
      render: (_, data) => viewStatus(data) // 直接返回viewStatus函数的结果
    },
    {
      title: '操作', key: 'classifyInfo', align: 'center', search: false, width: '13vw',
      render: (_, data) => {
        return (
          <>
            {/* 管理员可显示文章详情 */}
            {userType === 0 && <Button key="displayArticle" type='link' onClick={() => {
              setArticleData(data); setIsArticle(true); setArticleStatus(data.status === 2 ? true : false)
            }}>详情</Button>}
            {/* 调用前数据回填 form.setFieldsValue(data) */}
            {userType === 0 && data.status === 1 ? <Button type='link' key="reviewArticle" onClick={() => {
              setArticleData(data); setIsReview(true); form.setFieldsValue(data);
            }}>审核</Button> :
              data.status === 2 && <Button key="lookArticle" type='link'
                onClick={() => { history.push({ pathname: '/homePage/articleDetail', state: { articleId: data.articleId } }) }}
              >查看</Button>}
            {userType !== 0 && <Button key="editArticle" type='link'
              onClick={() => { history.push({ pathname: '/article', state: { editArticleId: data.articleId } }) }}
            >编辑</Button>}
            <Popconfirm title="确定要删除该文章吗？"
              key="deleteArticle"
              onConfirm={() => {
                dispatch({
                  type: 'articleManage/delArticle',
                  payload: {
                    articleIds: [data.articleId],
                  },
                })
              }} okText="确定" cancelText="取消">
              {/* danger 表示红色突出  type='link' 不显示边框  */}
              <Button danger type='link' key="deleteArticle" >删除</Button>
            </Popconfirm>
          </>
        );
      }
    },
  ].filter(Boolean);

  const viewStatus = ({ status }) => {
    // 0表示草稿，1表示发布等待审核，2表示发布成功，3表示不通过
    switch (status) {
      case 0:
        return <Tag key="0" icon={<FormOutlined />} color='volcano'>草稿</Tag>;
      case 1:
        return <Tag key="1" icon={<ExclamationCircleOutlined />} color='warning'>待审核</Tag>;
      case 2:
        return <Tag key="2" icon={<CheckCircleOutlined />} color='success'>已通过</Tag>;
      default:
        return <Tag key="3" icon={<CloseCircleOutlined />} color='error'>不通过</Tag>;
    }
  }

  const reviewArticle = (values) => {
    if (values.status === articleData.status) {
      message.error("请确定审核意见")
      return;
    }
    dispatch({
      type: 'articleManage/reviewArticle',
      payload: {
        articleIds: [articleData.articleId],
        status: values.status,
      },
    });
    setIsReview(false)
    setArticleStatus(false)
    form.resetFields();
  }

  const reloadTable = () => {
    dispatch({
      type: 'articleManage/queryArticle',
    })
  }

  return <>
    <ProTable actionRef={tableRef} defaultData={articleList} columns={columns} key="articleList"
      pagination={{
        defaultPageSize: 10, // 默认每页显示10条数据
        showSizeChanger: true, // 显示每页显示条数的选择器
        pageSizeOptions: ['10', '20', '50'], // 可供用户选择的每页显示条数选项
      }}
      options={{ reload: reloadTable, setting: true, density: true, }}
      toolBarRender={() => [<>{userType === 0 && <Tooltip title="该按钮可以通过全部未审核的文章"><Button key="reviewAllArticle" type="primary" onClick={() => {
        dispatch({
          type: 'articleManage/reviewAllArticle',
        });
      }}>一键审核</Button></Tooltip>}</>]}
      request={(params, sort, filter) => {
        return Promise.resolve({
          data: () => {
            return articleList?.filter((item) => {
              let result = true;
              Object.entries(params).forEach(([key, value]) => {
                if (key == "current" || key == "pageSize") {
                  return;
                }
                const dataKey = key.replace("search", "")
                if (item.hasOwnProperty(dataKey)) {
                  result = (result && item[dataKey].indexOf(value) != -1)
                }
              })
              return result;
            });
          },
          success: true,
        });
      }} />;
    {/* 详情里面显示标题、作者、获赞数、不喜欢、查看数、更新时间 */}
    <Modal key="articleInfo" title="文章信息" open={isArticle} onCancel={() => {
      setArticleData([]); setIsArticle(false);
    }} maskClosable={false}
      footer={[
        <Button key="close" onClick={() => { setArticleData([]); setIsArticle(false); }}>关闭</Button>,
      ]}>
      <Form name="basic" labelCol={{ span: 8, }} wrapperCol={{ span: 24, }} style={{ width: "80%" }}>
        <Form.Item label="文章标题" name="title">{articleData.title}</Form.Item>
        <Form.Item label="作者" name="displayName" >{articleData.displayName}</Form.Item>
        {articleStatus && <><Form.Item label="获赞数" name="like" >{articleData.like}</Form.Item>
          <Form.Item label="反对数" name="disLike" >{articleData.disLike}</Form.Item>
          <Form.Item label="收藏" name="collectCount" >{articleData.collectCount}</Form.Item>
          <Form.Item label="浏览量" name="view" >{articleData.view}</Form.Item></>}
        <Form.Item label="更新时间" name="updateTime">{articleData.updateTime}</Form.Item>
      </Form>
    </Modal>
    {/* 文章审核 主要针对 标题、作者、内容进行审核 */}
    <Modal key="reviewArticle" title="内容审核" open={isReview} onCancel={() => {
      setArticleData([]); setIsReview(false);
    }} maskClosable={false}
      footer={[
        <Button key="submit" type="primary" onClick={() => form?.submit()}>确定</Button>,
        <Button key="back" onClick={() => { setArticleData([]); setIsReview(false); }}>取消</Button>
      ]}>
      <Form form={form} name="basic" labelCol={{ span: 6, }}
        wrapperCol={{ span: 30, }} style={{ width: "90%" }} onFinish={reviewArticle}>
        <Form.Item label="文章标题" name="title">{articleData.title}</Form.Item>
        <Form.Item label="文章内容" name="content"><QuillEditor readOnly theme="bubble" /></Form.Item>
        <Form.Item label="作者" name="displayName">{articleData.displayName}</Form.Item>
        <Form.Item label="更新时间" name="updateTime">{articleData.updateTime}</Form.Item>
        <Form.Item label="审核意见" name='status' rules={[{ required: true, message: '请选择审核意见' }]}>
          <Radio.Group options={[{ label: "通过", value: 2 }, { label: "不通过", value: 3 }]} />
        </Form.Item>
      </Form>
    </Modal >
  </>
}

export default connect(({ articleManage, user }) => ({
  articleList: articleManage.articleList,
  userInfo: user.userInfo,
}))(ArticleManage);